package com.dupengcheng.auth.application.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.dupengcheng.auth.application.convert.AuthUserDTOConvert;
import com.dupengcheng.auth.application.dto.AuthUserDTO;
import com.dupengcheng.auth.common.entity.Result;
import com.dupengcheng.auth.domain.entity.AuthUserBO;
import com.dupengcheng.auth.domain.service.AuthUserDomainService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {

    @Resource
    private AuthUserDomainService authUserDomainService;


    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @RequestMapping("doLogin")
    public String doLogin(String username, String password) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对 
        if("zhang".equals(username) && "123456".equals(password)) {
           StpUtil.login(10001);


            return StpUtil.getTokenValue();
        }
        return "登录失败";
    }
    @RequestMapping("test")
    public String test(){
        return "OK";
    }

   //  查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {

        try{
            if (log.isInfoEnabled()){
                log.info("UserController:register:dto:{}",authUserDTO);
            }
            AuthUserBO authUserBO = AuthUserDTOConvert.INSTANCE
                    .convertDTOToBO(authUserDTO);
            authUserDomainService.register(authUserBO);
            return Result.ok("注册成功！");
        }
        catch (Exception e){
            log.error("UserController:register:error:{}",e.getMessage(),e);
            return Result.fail(e.getMessage());
        }
    }

}
